import Vue from 'vue'
import Vuex from 'vuex'
import {getRequest} from "../tuils/api";
import { Notification } from 'element-ui';
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';

Vue.use(Vuex)

const now = new Date();

const store =  new Vuex.Store({
    //声明的变量
    state:{
        //路由数组，从服务器上加载下来的菜单项
        routes:[],
        //聊天数据
        sessions:{},
        hrs:[],
        currentSession:null,
        //当前对象
        currentHr: JSON.parse(window.sessionStorage.getItem("user")),
        filterKey:'',
        stomp:null,
        isDot: {}

    },
    mutations:{
        INIT_CURRENTHR(state, hr) {
            state.currentHr = hr;
        },
        initRoutes(state,data) {
            state.routes = data;
        },
        changeCurrentSession (state,currentSession) {
            Vue.set(state.isDot, state.currentHr.username + '#' + currentSession.username, false);
            state.currentSession = currentSession;
        },
        //接收usertext.vue的消息对象(消息的添加)
        addMessage (state,msg) {

            console.log('state值: ', state);
            console.log('msg: ', msg);
            let mss = state.sessions[state.currentHr.username + '#' + msg.to];
            if (!mss) {
                // state.sessions[state.currentHr.username+'#'+msg.to] = [];
                //自动刷新
                Vue.set(state.sessions, state.currentHr.username + '#' + msg.to, []);
            }
            state.sessions[state.currentHr.username + '#' + msg.to].push({
                content: msg.content,
                date: new Date(),
                self: !msg.notSelf
            })
        },
        INIT_DATA (state) {
            //浏览器本地的历史聊天记录可以在这里完成
            let data = localStorage.getItem('vue-chat-session');
            if (data) {
                state.sessions = JSON.parse(data);
            }
        },
        INIT_HR(state,data) {
            state.hrs = data;
        },
    },
    //异步操作
    actions:{

        //websocket连接(消息的接收)
        connect(context) {
            //后端wsconfig的registerStompEndpoints
            context.state.stomp = Stomp.over(new SockJS('/ws/ep'));
            //发起连接
            context.state.stomp.connect({},success => {
                //参数1：监听地址；参数2：回调
                context.state.stomp.subscribe('/user/queue/chat',msg => {
                    let receiveMsg = JSON.parse(msg.body);
                    if (!context.state.currentSession || receiveMsg.from != context.state.currentSession.username) {
                        Notification.info({
                            title: '【' + receiveMsg.fromNickName + '】发来一条消息',
                            message: receiveMsg.content.length > 10 ? receiveMsg.content.substr(0, 10) : receiveMsg.content,
                            position: 'bottom-right'
                        })
                        Vue.set(context.state.isDot, context.state.currentHr.username + '#' + receiveMsg.from, true);
                    }
                    receiveMsg.notSelf = true;
                    receiveMsg.to = receiveMsg.from;
                    context.commit("addMessage",receiveMsg);
                })
            },error => {

            })
        },


        initData (context) {
            context.commit('INIT_DATA')
            getRequest("/chat/hrs").then(resp => {
                if (resp) {
                    context.commit("INIT_HR",resp);
                }
            })
        }
    }
})

//监听
store.watch(function (state) {
    return state.sessions
},function (val) {
    localStorage.setItem('vue-chat-session', JSON.stringify(val));
},{
    deep:true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
})


export default store;